<!DOCTYPE html>
<html lang="zh-cn" >
  <head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta
      name="author"
      content="awesome404"
    />
      
    <title>Docker与Mongodb ｜ 鹊木笔记</title>
    
    
    
    <meta name="description" content="手动方式 1. 准备 先使用 docker 命令拉取最新的 mongo 镜像 docker pull mongo:latest 2. 启动容器 方式一 使用以下命令，在启动容器的时候，配置数据库管理员账户，开启用户验证 docker run --name db -d -p 27017:27017 -e MONGO_INITDB_ROOT_USERNAME=admin -e MONGO_INITDB_ROOT_PASSWORD=123456 mongo 以上的用户名为 admin，密码为 123456，" />
      
    <meta
      name="keywords"
      content="Blog, 程序员, 前端"
    />
      <link
    rel="shortcut icon" href="https://awesome404.gitee.io/images/favicon.ico" />

    <link
      rel="stylesheet"
      type="text/css"
      media="screen"
      href="https://awesome404.gitee.io/css/normalize.css"
    />
    <link
      rel="stylesheet"
      type="text/css"
      media="screen"
      href="https://cdn.jsdelivr.net/npm/animate.css@4.1.0/animate.min.css"
    />
    <link rel="stylesheet" type="text/css" media="screen" href="https://awesome404.gitee.io/css/zozo.css" />
    <link
      rel="stylesheet"
      type="text/css"
      media="screen"
      href="https://cdn.jsdelivr.net/npm/remixicon@2.5.0/fonts/remixicon.css"
    />
    <link rel="stylesheet" type="text/css" media="screen" href="https://awesome404.gitee.io/css/highlight.css" />

    
    
  </head>
</html>


<body>
    <div class="main animate__animated animate__fadeInDown">
        
<div class="nav_container animated fadeInDown">
  <div class="site_nav" id="site_nav">
    <ul>
      
      <li>
        <a href="/">首页</a>
      </li>
      
      <li>
        <a href="/posts/">归档</a>
      </li>
      
      <li>
        <a href="/tags/">标签</a>
      </li>
      
      <li>
        <a href="/about/">关于</a>
      </li>
      
    </ul>
  </div>
  <div class="menu_icon">
    <a id="menu_icon">
      <i class="ri-settings-line"></i>
    </a>
  </div>
</div>

        <div class="header animated fadeInDown">
  <div class="site_title_container">
    <div class="site_title">
      <h1>
        <a href="https://awesome404.gitee.io">
          <span>鹊木笔记</span>
        </a>
      </h1>
    </div>
    <div class="description">
      <p class="sub_title">
        前端菜鸡的自我修养
      </p>
      <div class="my_socials">
         
        <a href="https://github.com/404Awesome" title="github" target="_blank"
          ><i class="ri-github-fill"></i
        ></a>
         
        <a
          href="https://awesome404.gitee.io/index.xml"
          type="application/rss+xml"
          title="rss"
          target="_blank"
          ><i class="ri-rss-fill"></i
        ></a>
      </div>
    </div>
  </div>
</div>

        <div class="content">
            <div class="post_page">
                <div class="post animate__animated animate__fadeInDown">
                    <div class="post_title post_detail_title">
                        <h2><a href='/posts/docker%E4%B8%8Emongodb/'>Docker与Mongodb</a></h2>
                        <span class="date">2022.03.24</span>
                    </div>
                    <div class="post_content markdown"><h1 id="手动方式">手动方式</h1>
<h2 id="1-准备">1. 准备</h2>
<blockquote>
<p>先使用 docker 命令拉取最新的 mongo 镜像</p>
<p>docker pull mongo:latest</p>
</blockquote>
<h2 id="2-启动容器">2. 启动容器</h2>
<h3 id="方式一">方式一</h3>
<p>使用以下命令，在启动容器的时候，配置数据库管理员账户，开启用户验证</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl">docker run --name db -d -p 27017:27017 -e <span class="nv">MONGO_INITDB_ROOT_USERNAME</span><span class="o">=</span>admin  -e <span class="nv">MONGO_INITDB_ROOT_PASSWORD</span><span class="o">=</span><span class="m">123456</span> mongo
</span></span></code></pre></div><p>以上的用户名为 admin，密码为 123456，生产环境建议使用复杂的密码，</p>
<p>进入容器</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl">docker <span class="nb">exec</span> -it db /bin/bash
</span></span></code></pre></div><p>操作数据库并验证</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl">mongo -u admin -p <span class="m">123456</span>
</span></span><span class="line"><span class="cl">use admin
</span></span><span class="line"><span class="cl">db.auth<span class="o">(</span><span class="s1">&#39;admin&#39;</span>, <span class="s1">&#39;123456&#39;</span><span class="o">)</span>
</span></span></code></pre></div><p>返回 1 代表成功, 使用 exit 命令，退出数据库操作</p>
<h3 id="方式二">方式二</h3>
<p>使用以下命令，需在启动后，手动进入容器，进行添加账户操作</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl">docker run --name db -d -p 27017:27017 mongo --auth
</span></span></code></pre></div><p>进入容器并操作数据库</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl">docker <span class="nb">exec</span> -it db mongo admin
</span></span></code></pre></div><p>添加账户</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-fallback" data-lang="fallback"><span class="line"><span class="cl">db.createUser({ user:&#39;admin&#39;,pwd:&#39;123456&#39;,roles:[ { role:&#39;userAdminAnyDatabase&#39;, db: &#39;admin&#39;},&#34;readWriteAnyDatabase&#34;]});
</span></span></code></pre></div><p>测试是否添加成功</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl">db.auth<span class="o">(</span><span class="s1">&#39;admin&#39;</span>, <span class="s1">&#39;123456&#39;</span><span class="o">)</span>
</span></span></code></pre></div><p>返回 1 代表成功, 使用 exit 命令，退出数据库操作</p>
<blockquote>
<p>完成以上任意一种后，还需更改 mongod 的配置文件，使其他容器可以访问 mongo 数据库，使用如下命令安装 vim</p>
</blockquote>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl">apt-get update
</span></span><span class="line"><span class="cl">apt-get install vim   <span class="o">[</span>Y<span class="o">]</span>确认	
</span></span></code></pre></div><p>使用如下命令修改 mongod 配置文件</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl">vi etc/mongod.conf.orig
</span></span><span class="line"><span class="cl"><span class="c1"># 修改以下内容</span>
</span></span><span class="line"><span class="cl">net:
</span></span><span class="line"><span class="cl">  port: <span class="m">27017</span>
</span></span><span class="line"><span class="cl">  bindIp: 127.0.0.1  <span class="c1"># 修改前</span>
</span></span><span class="line"><span class="cl">  bindIp: 0.0.0.0    <span class="c1"># 修改后</span>
</span></span></code></pre></div><p>保存并退出容器即可</p>
<h2 id="3-使用-node-操作-mongo">3. 使用 Node 操作 Mongo</h2>
<h3 id="代码结构">代码结构</h3>
<img src="/img/post/docker/docker与mongo_1.png">
<blockquote>
<p>监听 3000 端口，请求 api 为 /user，为了方便使用 Get 方式传递参数，将数据持久化到 mongo</p>
</blockquote>
<img src="/img/post/docker/docker与mongo_2.png">
<blockquote>
<p>使用 mongoose 操作 mongo</p>
<p>mongoose.connect(&ldquo;mongodb://账户名:密码@容器名称/数据库?authSource=admin&rdquo;)</p>
</blockquote>
<img src="/img/post/docker/docker与mongo_3.png">
<blockquote>
<p>使用 Dockerfile 打包镜像，步骤如上图所示</p>
<p>docker build -t api .</p>
<p>npm start 命令  ==  nodemon ./src/app.js</p>
</blockquote>
<h3 id="启动容器">启动容器</h3>
<p>使用以下命令，启动容器并关联 mongo 数据库</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl">docker run --name nodeapi -d -p 3000:3000 --link db api
</span></span></code></pre></div><h3 id="测试功能">测试功能</h3>
<p>打开浏览器，在地址栏输入数据以便于查看效果</p>
<img src="/img/post/docker/docker与mongo_4.png">
<blockquote>
<p>功能一切正常，通过 Node 容器访问到了 Mongo 数据库</p>
</blockquote>
<h1 id="dockercompose方式">DockerCompose方式</h1>
<blockquote>
<p>docker-compose.yml 文件如下</p>
</blockquote>
<img src="/img/post/docker/docker与mongo_5.png">
<blockquote>
<p>通过 docker-compose up 命令可以快速启动服务</p>
</blockquote>
</div>
                    <div class="post_footer">
                        
                        
                        <div id="link">
                            <p>本博客所有文章除特别声明外，均采用 CC BY-SA 3.0协议 。转载请注明出处！</p>
                            <p><span id="link_href"></span><i class="ri-file-copy-2-line link_btn"></i></p>
                        </div>
                        
                        <div class="meta">
                            <div class="info">
                                <span class="field tags">
                                    <i class="ri-price-tag-2-line"></i>
                                    
                                    <a href="https://awesome404.gitee.io/tags/docker/">Docker</a>
                                    
                                    <a href="https://awesome404.gitee.io/tags/mongodb/">Mongodb</a>
                                    
                                    <a href="https://awesome404.gitee.io/tags/node/">Node</a>
                                    
                                </span>
                            </div>
                        </div>
                        
                    </div>
                </div>
                
                
            </div>
        </div>
    </div>
    <a id="back_to_top" href="#" class="back_to_top"><i class="ri-arrow-up-s-line"></i></a>
    
<style>
  #hitokoto {
    overflow: hidden;
    margin: 0 auto;
    width: 80%;
    text-overflow: ellipsis;
    white-space: nowrap;
    font-size: 16px;
    color: #424242;
  }

  .footer {
    padding: 30px 0px;
  }
</style>

<footer class="footer">
  <p id="hitokoto">:D 获取中...</p>
</footer>

<script>
  fetch("https://v1.hitokoto.cn")
    .then((response) => response.json())
    .then((data) => {
      const hitokoto = document.getElementById("hitokoto");
      hitokoto.href = "https://hitokoto.cn/?uuid=" + data.uuid;
      hitokoto.innerText = data.hitokoto;
    })
    .catch((err) => err);
</script>

    <script src="https://awesome404.gitee.io/js/jquery-3.5.1.min.js"></script>
<link href="https://awesome404.gitee.io/css/fancybox.min.css" rel="stylesheet">
<script src="https://awesome404.gitee.io/js/fancybox.min.js"></script>
<script src="https://awesome404.gitee.io/js/zozo.js"></script>




</body>


<script>
    (function (){
        
        function handleIcon (remove, target){
            this.classList.remove(remove);
            this.classList.add(target);
        }

        let hrefEl = document.getElementById("link_href");
        let copyBtn = document.getElementsByClassName("link_btn")[0];
        if (hrefEl){
            hrefEl.innerText = `文章链接: ${location.href}`;
            
            copyBtn.onclick = (event) => {
                
                navigator.clipboard.writeText(`文章转载自: ${location.href}`)
                
                handleIcon.call(event.target, "ri-file-copy-2-line", "ri-check-line");
                let timer = setTimeout(() => {
                    handleIcon.call(event.target, "ri-check-line", "ri-file-copy-2-line");
                    clearTimeout(timer)
                }, 1000)
            }
        }
    })();
</script>
</html>